﻿//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.IO;
using System.Text;


namespace EffiProz.Core.Lib.IO
{

    /**
     * This class is a replacement for both java.io.ByteArrayInputStream
     * (without synchronization) and java.io.DataInputStream
     *
     * @author fredt@users
     * @version 1.7.2
     * @since 1.7.2
     */
    public class ByteArrayInputStream : Stream
    {

        protected byte[] buf;
        protected int pos;
        protected int _mark = 0;
        protected int count;


        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException();
        }


        public override void Flush()
        {            
        }


        public override long Position
        {
            get
            {
                return pos;
            }

            set
            {
                pos = (int)value;
            }
        }

        public override long Length
        {
            get
            {
                return count;
            }
        }

        public override bool CanRead
        {
            get
            {
                return true;
            }
        }

        public override bool CanSeek
        {
            get
            {
                return false;
            }
        }

        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotSupportedException();
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return read(buffer, offset, count);
        }
        
        public override void SetLength(long value)
        {
            count = (int)value;
        }



        public ByteArrayInputStream()
        {

            this.buf = new byte[4096];
            this.pos = 0;
            this.count = buf.Length;
        }

        public ByteArrayInputStream(byte[] buf)
        {

            this.buf = buf;
            this.pos = 0;
            this.count = buf.Length;
        }

        public ByteArrayInputStream(byte[] buf, int offset, int length)
        {

            this.buf = buf;
            this.pos = offset;
            this.count = Math.Min(offset + length, buf.Length);
            this._mark = offset;
        }

        // methods that implement java.io.DataInput
        public virtual void readFully(byte[] b)
        {
            readFully(b, 0, b.Length);
        }

        public virtual void readFully(byte[] b, int off,
                                    int len)
        {

            if (len < 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            int n = 0;

            while (n < len)
            {
                int count = read(b, off + n, len - n);

                if (count < 0)
                {
                    throw new InvalidOperationException();
                }

                n += count;
            }
        }

        public virtual bool readBool()
        {
            int ch = read();

            if (ch < 0)
            {
                throw new InvalidOperationException();
            }

            return (ch != 0);
        }

        public virtual byte readByte()
        {

            int ch = read();

            if (ch < 0)
            {
                throw new InvalidOperationException();
            }

            return (byte)ch;
        }

        public virtual int readUnsignedByte()
        {

            int ch = read();

            if (ch < 0)
            {
                throw new InvalidOperationException();
            }

            return ch;
        }

        public virtual short readShort()
        {
            if (count - pos < 2)
            {
                pos = count;
                throw new InvalidOperationException();
            }

            short val = BitConverter.ToInt16(buf, pos);
            pos += 2;

            return val;
        }

        public virtual int readUnsignedShort()
        {
            if (count - pos < 2)
            {
                pos = count;
                throw new InvalidOperationException();
            }

            int val = BitConverter.ToInt16(buf, pos);
            pos += 2;

            if (val < 0)
            {
                throw new InvalidOperationException();
            }

            return val;
        }

        public virtual char readChar()
        {
            if (count - pos < 2)
            {
                pos = count;
                throw new InvalidOperationException();
            }

            char val = BitConverter.ToChar(buf, pos);
            pos += 2;

            return val;
        }

        public virtual int readInt()
        {

            if (count - pos < 4)
            {
                pos = count;
                throw new InvalidOperationException();
            }
         
            int val = BitConverter.ToInt32(buf, pos);
            pos += 4;
            return val;
        }

        public virtual Decimal readDecimal()
        {
            int[] bits = new int[4];
            bits[0] = readInt();
            bits[1] = readInt();
            bits[2] = readInt();
            bits[3] = readInt();

            Decimal d = new Decimal(bits);
            return d;
        }

        public virtual long readLong()
        {
            if (count - pos < 8)
            {
                pos = count;
                throw new InvalidOperationException();
            }

            long val = BitConverter.ToInt64(buf, pos);
            pos += 8;
            return val;
        }

        public virtual float readFloat()
        {
#if !SILVERLIGHT
             return (float)BitConverter.Int64BitsToDouble(readLong());
#else
            byte[] bytes = new byte[8];
            Read(bytes, 0, 8);
            return (float)BitConverter.ToDouble(bytes, 0);
#endif
           
        }

        public virtual double readDouble()
        {
#if !SILVERLIGHT
             return BitConverter.Int64BitsToDouble(readLong());
#else
            byte[] bytes = new byte[8];
            Read(bytes, 0, 8);
            return BitConverter.ToDouble(bytes, 0);
#endif
        }

        public virtual int skipBytes(int n)
        {
            return (int)skip(n);
        }

        public virtual string readLine()
        {

            /** @todo: this will probably be useful */
            throw new Exception("not implemented.");
        }

        public string readUTF()
        {

            int bytecount = readUnsignedShort();

            if (pos + bytecount >= count)
            {
                throw new InvalidOperationException();
            }

            string result = Encoding.UTF8.GetString(buf, pos, bytecount);

            pos += bytecount;

            return result;
        }

        // methods that extend java.io.InputStream
        public byte read()
        {
            return (byte)( (pos < count) ? buf[pos++] : -1 );
        }

        public int read(byte[] b, int off, int len)
        {

            if (pos >= count)
            {
                return -1;
            }

            if (pos + len > count)
            {
                len = count - pos;
            }

            if (len <= 0)
            {
                return 0;
            }

            Array.Copy(buf, pos, b, off, len);

            pos += len;

            return len;
        }

        public long skip(long n)
        {

            if (pos + n > count)
            {
                n = count - pos;
            }

            if (n < 0)
            {
                return 0;
            }

            pos += (int)n;

            return n;
        }

        public int available()
        {
            return count - pos;
        }

        public bool markSupported()
        {
            return true;
        }

        public void mark(int readAheadLimit)
        {
            _mark = pos;
        }

        public virtual void reset()
        {
            pos = _mark;
        }

        public void close() { }
    }
}
